package com.mes.controller;

import com.license.rsa.RSALicenseManager;
import com.mes.common.FormatUtilities;
import com.mes.entity.User;
import com.yy.base.common.action.BaseCtrl;
import com.yy.base.log.Logger;
import com.yy.base.log.LoggerFactory;
import com.yy.base.page.Message;
import com.yy.base.servlet.UserListener;
import com.yy.base.util.ObjectUtil;
import com.yy.base.util.SessionInfo;
import com.yy.base.util.StringUtil;
import com.yy.base.util.UserUtil;
import com.yy.system.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Controller
@SuppressWarnings("unchecked")
@RequestMapping(value = "/loginController")
public class LoginController extends BaseCtrl {
	private Logger log = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private LoginService service;

	/**
	 * 登录系统
	 */
	@ResponseBody
	@RequestMapping(value="/login.html")
	public Message login(HttpServletRequest request) {
		Message message = new Message();
		try {
			if(RSALicenseManager.validate()){
				String userCode = request.getParameter("userCode");
				String password = request.getParameter("password");

				if (userCode != null) {
					User user = service.login(userCode);
					if (user != null) {
						String pwd = FormatUtilities.sha1Base64(password);
						if (user.getPassword().equals(pwd)) {
							HttpSession session = request.getSession(true);
							session.setMaxInactiveInterval(60 * 60 * 4);//设置session4小时失效
							session.setAttribute(UserUtil.USERSESSION, user);
							session.setAttribute("userId", user.getId());

							UserListener.sessionCreated(session);
							message.setOkMessage("ok");
							SessionInfo.setUser(user);

							String orgId = setUserOrgId(request, user.getId());
							if (orgId != null) {
								Map map = service.getLoginInfos(user, (String)request.getSession().getAttribute("orgId"));
								session.setAttribute("orgName", map.get("NAME"));
							}
						} else {
							message.setErrorMessage("用户名或密码错误!");
						}
					} else {
						message.setErrorMessage("用户名或密码错误!");
					}
				} else {
					message.setErrorMessage("登录方式异常!");
				}
			}else{
				message.setErrorMessage("您的license已失效，请联系管理员!");
			}
		} catch (Exception e) {
			log.error(e);
			message.setErrorMessage("登录失败!");
		}
		return message;
	}

	/**
	 * 根据当前登录的用户信息、或IP地址，获取用户的车间ID
	 */
	private String setUserOrgId(HttpServletRequest request, String userId) {
		String sql = "select get_User_Workshop(?) orgId from dual";
		Map<String, Object> map = service.getDao().queryUnique(sql, userId);

		String orgId = null;
		if (map == null || map.get("ORGID") == null) {
			String ip = StringUtil.getClientIp(request);

			if (ip != null && ip.split("\\.").length == 4) {
				sql = "select emes_parameter_id from emes_parameter where code like 'DC%-IP' and value = ?";
				map = service.getDao().queryUnique(sql, ip.split("\\.")[2]);

				if (map != null) {
					orgId = (String)map.get("Emes_PARAMETER_ID");
				}
			}
		} else {
			orgId = (String)map.get("ORGID");
		}

		request.getSession().setAttribute("orgId", orgId);
		return orgId;
	}

	/**
	 * 系统菜单权限
	 */
	@ResponseBody
	@RequestMapping(value="/getMenus.html")
	public Message getMenus(HttpServletRequest request) {
		Message message = new Message();
		try {
			List list = service.getMenus(this.getLoginUser(request).getId());
			message.formartData(ObjectUtil.listEntityToMap(list));
		} catch (Exception e) {
			log.error(e);
			message.setErrorMessage("获取菜单失败!");
		}
		return message;
	}
	/**
	 * 获取用户信息
	 */
	@ResponseBody
	@RequestMapping(value="/getUserInfo.html")
	public Message getUserInfo(HttpServletRequest request) {
		Message message = new Message();
		try {
			message.setOkMessage(this.getLoginUser(request).getName());
		} catch (Exception e) {
			log.error(e);
			message.setErrorMessage("获取用户信息失败!");
		}
		return message;
	}
	/**
	 * 退出系统
	 */
	@ResponseBody
	@RequestMapping(value="/loginOut.html")
	public Message loginOut(HttpServletRequest request) {
		Message message = new Message();
		try {
			request.getSession().invalidate();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
		}
		return message;
	}

	@PostMapping("/timeout")
	@ResponseBody
	public boolean isSessionTimeOut(HttpServletRequest request){
		return request.getSession().getAttribute(UserUtil.USERSESSION) == null;
	}
}